package log_stash

import (
	"blog_go/global"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type BehaviorLog struct {
	ip     string `json:"ip"`
	addr   string `json:"addr"`
	userId uint   `json:"user_id"`
}

func (BehaviorLog) SendMsg() {

}
func New(ip string, token string) *BehaviorLog {
	// 解析token
	claims, err := utils.ParseToken(token)
	var userID uint
	if err == nil {
		userID = claims.UserID
	}
	addr := ""
	//addr := utils.GetAddr(ip)
	// 拿到用户id
	return &BehaviorLog{
		ip:     ip,
		addr:   addr,
		userId: userID,
	}
}

func NewBLogByGin(c *gin.Context) *BehaviorLog {
	ip := c.ClientIP()
	token := c.Request.Header.Get("token")
	return New(ip, token)
}

func (log BehaviorLog) Debug(content string) {
	log.send(DebugLevel, content)
}
func (log BehaviorLog) Info(content string) {
	log.send(InfoLevel, content)
}
func (log BehaviorLog) Warn(content string) {
	log.send(WarnLevel, content)
}
func (log BehaviorLog) Error(content string) {
	log.send(ErrorLevel, content)
}

func (log BehaviorLog) send(level Level, content string) {
	model := &LogStashModel{
		IP:      log.ip,
		Addr:    log.addr,
		Level:   level,
		Content: content,
		UserID:  log.userId,
	}
	if !sync {
		err := global.DB.Create(model).Error
		if err != nil {
			logrus.Error("行为日志错误", *model, err)
		}
	} else {
		logSyncDBChan <- model
	}

}
